import os, zipfile, shutil
import utils, web

EXTERNAL_DIR = "./external/"

class Executa():
	def __init__(self, code, donde=None, luego=[]):
		self.code = code
		self.donde = donde
		self.luego = luego
	def addExecutaLuego(self, ejecuta):
		self.luego += [ejecuta]
	def ejecuta(self):
		antes = None
		if self.donde:
			antes = os.getcwd()
			os.chdir(self.donde)
		os.system(self.code)
		if antes:
			os.chdir(antes)
		for accion in self.luego:
			accion.ejecuta()

class ApkTool(Executa):
	def __init__(self, file, sample_report_dir):
		Executa.__init__(self, "java -jar "+EXTERNAL_DIR+"apktool.jar -v d -f "+file+" "+sample_report_dir+"./smali")

class AntiLVL(Executa):
	def __init__(self, file, sample_report_dir):
		Executa.__init__(self, None, EXTERNAL_DIR+"AntiLVL/")
		destino = sample_report_dir
		if destino.startswith("./"):
			destino = os.getcwd()+"/"+destino
		
		if file.startswith("./"): file = os.getcwd()+"/"+file
		(name, ext) = file.rsplit("/", 1)[-1].rsplit(".", 1)
		self.dump = "./"+name+"-dump"

		self.code = "java -jar antilvl.jar -f -s -d "
		self.code += file#+" "+destino
		self.code += " > "+destino+"./antilvl.info"

	def ejecuta(self):
		Executa.ejecuta(self)
		if os.path.isdir(self.donde + self.dump):
			shutil.rmtree(self.donde + self.dump)



class Ddx(Executa):
	def __init__(self, file, sample_report_dir):
		Executa.__init__(self, None)
		if not os.path.isdir(sample_report_dir+"ddx/"): os.mkdir(sample_report_dir+"ddx/")
		self.code = "java -jar "+EXTERNAL_DIR+"ddx.jar -o -D -r -d "+sample_report_dir+"ddx/ "+file

class Dex2Jar(Executa):
	#file ruta absoluta o relativa al destino
	def __init__(self, file, sample_report_dir):
		Executa.__init__(self, None)
		dir = EXTERNAL_DIR
		if EXTERNAL_DIR.startswith("."):
			dir = os.getcwd() + EXTERNAL_DIR
		if file.startswith("."):
			file = os.getcwd() + file
		try:
			os.uname()#"UNIX"
			self.code = dir+"dex2jar/dex2jar.sh "+file
		except:#"WIN"
			self.code = dir+"dex2jar/dex2jar_.bat "+file
		self.donde = sample_report_dir

class Decompiler():
	def __init__(self):
		self.suported = {"dex":[Dex2Jar, Ddx], "apk":[ApkTool,AntiLVL]}

	def decompile(self, file):
		file = file.replace("\\","/")#Unificamos a formato UNIX
		(md5, ext) = file.rsplit("/", 1)[-1].rsplit(".", 1)
		destino = utils.REPORTS_DIR + md5 + "/"
		if os.path.isdir(destino): return #YA ESTA DECOMPILADO
		os.mkdir(destino)
		if not ext in self.suported: return
		if ext == "apk" and zipfile.is_zipfile(file):
			zip = zipfile.ZipFile(file, 'r')
			if not zip.testzip():
				elementos = zip.namelist()
				if "classes.dex" in elementos and "AndroidManifest.xml" in elementos:
					shutil.copy(file, destino+"./sample.apk")
					zip.extract("classes.dex", destino)
					for clase in self.suported["apk"]:
						clase(destino+"./sample.apk", destino).ejecuta()
			zip.close()
		elif ext == "dex":
			shutil.copy(file, destino+"./classes.dex")
		else: return
		for clase in self.suported["dex"]:
			clase(destino+"./classes.dex", destino).ejecuta()




#decompiler("./file_upload\de6aa103a48357e51c44336d5470b733.apk")
#dec = Decompiler()
#dec.decompile("./file_upload/dff960b303639e4a7cdd507bda8c88bb.apk")
#file = "./file_upload/b2e3a256e0cd139386b1b64530b3cf80.apk".replace("\\","/")#Unificamos a formato UNIX
#(md5, ext) = file.rsplit("/", 1)[-1].rsplit(".", 1)
#destino = utils.REPORTS_DIR + md5 + "/"
#AntiLVL(file, destino).ejecuta()
